package com.topscomm.main.config;

import com.topscomm.basic.exception.BusinessException;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.constant.TapHttpErrorCode;
import com.topscomm.tap.constant.TapHttpStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
  * 处理全局ServiceException
  * @author xinfushuo
  * @date 2022/8/30
  * @modify
  */
@Slf4j
@RestControllerAdvice
public class ServiceExceptionHandler {
    /**
     * @description:ServiceException异常
     * @param e
     * @return
     * @author: xinfushuo
     * @date: 2022年8月30日下午9:43:11
     * @modify:
     */
    @ExceptionHandler(ServiceException.class)
    public ResponseEntity<ResponseResult<Object>> handleServiceException(ServiceException e) {
        String errorMessage = e.getMessage();
        return buildResponseEntity(HttpStatus.OK, ResponseResult.error(TapHttpStatus.HTTP_OK, TapHttpErrorCode.ERROR, errorMessage));
    }
    /**
     * @description:Business异常
     * @param e
     * @return
     * @author: xinfushuo
     * @date: 2022年8月30日下午9:43:11
     * @modify:
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<ResponseResult<Object>> handleBussinessException(BusinessException e) {
        String errorMessage = e.getMessage();
        return buildResponseEntity(HttpStatus.OK, ResponseResult.error(TapHttpStatus.HTTP_OK, TapHttpErrorCode.ERROR, errorMessage));
    }
    @ExceptionHandler(ServletRequestBindingException.class)
    public ResponseEntity<ResponseResult<Object>> handleMethodHeaderException(ServletRequestBindingException e) {
        String errorMessage = e.getMessage();
        return buildResponseEntity(HttpStatus.OK, ResponseResult.error(TapHttpStatus.HTTP_OK, TapHttpErrorCode.ERROR, errorMessage));
    }

    /**
     * @description:异常返回内容构建
     * @param status
     * @param result
     * @return
     * @modify:
     */
    protected ResponseEntity<ResponseResult<Object>> buildResponseEntity(HttpStatus status, ResponseResult<Object> result) {
        return new ResponseEntity<>(result, status);
    }
}

